from flask import Blueprint, request, jsonify, render_template, session
from decorator import login_required
from bt import Bt_api
from flask import current_app

blueprint = Blueprint('reverse_proxy', __name__, url_prefix='/reverse_proxy')

@blueprint.route("/", methods=['GET', 'POST'], endpoint='reverse_proxy_main')
@login_required
def reverse_proxy_main():
    if request.method == 'POST':
        # 获取表单数据（简化版本）
        action = request.form.get('action', 'CreateProxy')
        proxyname = request.form.get('proxyname', '')
        proxysite = request.form.get('proxysite', '')
        todomain = request.form.get('todomain', '')
        
        # 实例化宝塔API对象
        bt_api = Bt_api(session.get('bt_url'), session.get('bt_key'))
        
        # 调用宝塔API创建反向代理
        try:
            result = bt_api.create_proxy(
                action=action,
                proxyname=proxyname,
                proxysite=proxysite,
                todomain=todomain,
                sitename=session.get('bt_web', '')  # 添加网站名称参数
            )
            return jsonify(result)
        except Exception as e:
            return jsonify({
                'status': False,
                'msg': f'反向代理创建失败: {str(e)}'
            })
    
    # GET请求返回页面，同时获取反向代理列表
    cdn = current_app.config['CDN']
    
    # 获取反向代理列表
    try:
        bt_api = Bt_api(session.get('bt_url'), session.get('bt_key'))
        proxy_list_result = bt_api.get_proxy_list(session.get('bt_web', ''))
        proxy_list = proxy_list_result if isinstance(proxy_list_result, list) else []
    except Exception as e:
        proxy_list = []
    
    return render_template('reverse_proxy.html', cdn=cdn, proxy_list=proxy_list)

# 删除反向代理的路由
@blueprint.route("/delete", methods=['POST'], endpoint='delete_proxy')
@login_required
def delete_proxy():
    # 获取表单数据
    proxyname = request.form.get('proxyname', '')
    
    # 实例化宝塔API对象
    bt_api = Bt_api(session.get('bt_url'), session.get('bt_key'))
    
    # 调用宝塔API删除反向代理
    try:
        result = bt_api.remove_proxy(
            proxyname=proxyname,
            sitename=session.get('bt_web', '')  # 添加网站名称参数
        )
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'status': False,
            'msg': f'反向代理删除失败: {str(e)}'
        })